﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace ServiceDesk.DAL
{
    public class ServiceDeskSessionFactory
    {
        static ServiceDeskSessionFactory()
        {
            ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ServiceDeskDB"].ConnectionString;
            
        }

        public ServiceDeskSessionFactory()
        {
            SessionFactory = CreateSessionFactory(ConnectionString);
        }

        public readonly ISessionFactory SessionFactory;
        
  
        
        //public const string ConnectionString = "server=.\\SQLExpress;" + "database=ServiceDesk;" + "Integrated Security=SSPI;";
        public readonly static string ConnectionString;



        private FluentConfiguration Mapping(string connString)
        {
            return
                Fluently.Configure()
                    .Database(MsSqlConfiguration
                                  .MsSql2008
                                  .ConnectionString(connString).ShowSql())
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ServiceDeskSessionFactory>());
        }

        private ISessionFactory CreateSessionFactory(string connString)
        {
            return 
                Mapping(connString)
                    .BuildSessionFactory();
            
        }
        public void CreateDb(string connString)
        {
            Mapping(connString)
                .ExposeConfiguration(CreateSchema)
                .BuildConfiguration();
        }
        private void CreateSchema(Configuration cfg)
        {
            var schemaExport = new SchemaExport(cfg);
            schemaExport.Drop(true, true);
            schemaExport.Create(true, true);
        }
    }
}
